//
//  NSString+Extension.m
//  XCY
//
//  Created by XCY
//  Copyright (c) 2015年 HQ. All rights reserved.
//

#import "NSString+Extension.h"

NSString * const CHINAPYNUM = @"\\w+";  //禁止输入特殊字符
NSString * const NUMBERS = @"0123456789\b";   //只能输入数字
NSString * const NUMAZ = @"^[A-Za-z0-9]+$";  //数字和字母
NSString * const NUMDoubleTwo = @"^([1-9][\\d]{0,100}|0)(\\.[\\d]{0,2})?$";  //带两位小数的金额
@implementation NSString (Extension)
- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

- (NSString *)yearMonthWithDateFormat:(NSString *)dateFormat
{
    if (self == nil || self.length == 0) return @"";
    //2016-09-20T17:12:122
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    
    dateFormatter.dateFormat = dateFormat;
    NSDate *formatterDate = [dateFormatter dateFromString:self];
    NSDate *now = [NSDate date];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents *formatterComp = [calendar components:unit fromDate:formatterDate];
    NSDateComponents *nowComp = [calendar components:unit fromDate:now];
    
    
    /**
     *  本月、5月、2016年5月
     */
    if (formatterComp.year == nowComp.month) {  //同一年
        if (formatterComp.month == nowComp.month) { //本月
            return @"本月";
        }else{
            dateFormatter.dateFormat = @"MM";
            NSInteger month = [[dateFormatter stringFromDate:formatterDate] integerValue];
            return [NSString stringWithFormat:@"%ld月", month];
        }
    }else{ //其它日子
        dateFormatter.dateFormat = @"yyyy年M月";
        return [dateFormatter stringFromDate:formatterDate];
    }
}

/**
 *  134****7890
 */
- (NSString *)phoneShield
{
    if (self && self.length >= 11) {
        return [NSString stringWithFormat:@"%@****%@", [self substringToIndex:3], [self substringWithRange:NSMakeRange(7, 4)]];
    }
    return self;
}

/**
 *  手机号码的有效性判断
 *  检测是否是手机号码
 */
- (BOOL)isMobileNumber
{
    /**
     * 手机号码
     * 移动：134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通：130,131,132,145,152,155,156,1709,171,176,185,186
     * 电信：133,134,153,1700,177,180,181,189
     */
    NSString * MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString * CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[0]|7[8]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,152,155,156,1709,171,176,185,186
     */
    NSString * CU = @"^1(3[0-2]|4[5]|5[56]|709|7[1]|7[6]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,134,153,1700,177,180,181,189
     */
    NSString * CT = @"^1(3[34]|53|77|700|8[019])\\d{8}$";
    /**
     * 大陆地区固话及小灵通
     * 区号：010,020,021,022,023,024,025,027,028,029
     * 号码：七位或八位
     */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:self] == YES)
        || ([regextestcm evaluateWithObject:self] == YES)
        || ([regextestct evaluateWithObject:self] == YES)
        || ([regextestcu evaluateWithObject:self] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


//去除首尾空格
- (NSString *)trim{
    return [self stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

//是否不为空
+ (BOOL)isNotEmptyWithStr:(NSString *)str
{
    return str && [[str trim] length] != 0;
}

//是否为空
+ (BOOL)isEmptyWithStr:(NSString *)str
{
    return !str || [[str trim] length] == 0;
}

//是否大于0
+ (BOOL)isValidGreaterZeroWithNum:(NSInteger)num
{
    BOOL isValid = NO;
    if (num > 0) {
        isValid = YES;
    }
    return isValid;
}

//字典转json字符串   类似  "StudentName" : "Yay",
+ (NSString *)dicToStringdic:(id)dic{
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

/**
 *  传入正则表达式，一般用于限制特殊字符
 */
- (NSString *)doNotWantString:(NSString *)string block:(void (^)())block
{
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:string];
    NSArray *array = [self componentsSeparatedByCharactersInSet: doNotWant];
    if (array.count > 1) {
        if (block) {
            block();
        }
    }
    return [array componentsJoinedByString:@""];
}

/**
 *  正则表达式，控制中文、字母、数字等
 */
- (NSString *)regexDoNotWantPattern:(NSString *)pattern block:(void (^)())block
{
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    
    NSMutableString *stringM = [NSMutableString string];
    for (NSTextCheckingResult *result in results) {
        [stringM appendString:[self substringWithRange:result.range]];
    }
    if (self.length != stringM.length) {
        if (block) {
            block();
        }
    }
    return stringM;
}

//字符串拿过来去掉特殊的字符
-(NSString *)removeSpecial{
//    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"（）() -"];
    NSString *temstr1 = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *temstr2 = [temstr1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
    NSString *temstr3 = [temstr2 stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSString *temstr4 = [temstr3 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return temstr4;
}

//手机号码格式化3-4-4
- (NSString *)phone344Format
{
    return [self stringFormatWithLengths:@[@3, @4] appdStr:@"-"];
}

//银行卡号6 6 6
- (NSString *)bankNumFormat
{
    return [self stringFormatWithLengths:@[@6] appdStr:@" "];
}

- (NSString *)stringFormatWithLengths:(NSArray *)lengths appdStr:(NSString *)appdStr
{
    if (lengths.count <= 0) return self;
    
    NSString *text = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newString = @"";
    NSInteger length = [lengths[0] integerValue];
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, length)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == length) {
            newString = [newString stringByAppendingString:appdStr];
        }
        
        text = [text substringFromIndex:MIN(text.length, length)];
        if (lengths.count > 1) {
            length = [lengths[1] integerValue];
        }
    }
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:NUMBERS];
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    return newString;
}


/**
 *  传入数字限制，一般用于限制只能输入数字
 */
- (NSString *)doNotWantString2:(NSString *)string block:(void (^)())block
{
    NSCharacterSet *doNotWant = [[NSCharacterSet characterSetWithCharactersInString:string] invertedSet];
    NSArray *array = [self componentsSeparatedByCharactersInSet: doNotWant];
    if (array.count > 1) {
        if (block) {
            block();
        }
    }
    return [array componentsJoinedByString:@""];
}

//去除价格开头的0,,
- (NSInteger)getPrice
{
    return [self integerValue];
}

//处理json格式的字符串中的换行符、回车符
- (NSString *)deleteSpecialCode
{
    NSString *string = [self stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    return string;
}

//金额大写
- (NSString *)digitUppercase
{
    if (!self) {
        return nil;
    }
    
    NSMutableString *moneyStr = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%.2f",[self doubleValue]]];
    NSArray *MyScale=@[@"分", @"角", @"元", @"拾", @"佰", @"仟", @"万", @"拾", @"佰", @"仟", @"亿", @"拾", @"佰", @"仟", @"兆", @"拾", @"佰", @"仟" ];
    NSArray *MyBase=@[@"零", @"壹", @"贰", @"叁", @"肆", @"伍", @"陆", @"柒", @"捌", @"玖"];
    
    NSArray *integerArray = @[@"拾", @"佰", @"仟", @"万", @"拾万", @"佰万", @"仟万", @"亿", @"拾亿", @"佰亿", @"仟亿", @"兆", @"拾兆", @"佰兆", @"仟兆"];
    
    
    NSMutableString * M = [[NSMutableString alloc] init];
    [moneyStr deleteCharactersInRange:NSMakeRange([moneyStr rangeOfString:@"."].location, 1)];
    for(NSInteger i=moneyStr.length;i>0;i--)
    {
        NSInteger MyData=[[moneyStr substringWithRange:NSMakeRange(moneyStr.length-i, 1)] integerValue];
        [M appendString:MyBase[MyData]];
        
        //判断是否是整数金额
        if (i == moneyStr.length) {
            NSInteger l = [[moneyStr substringFromIndex:1] integerValue];
            if (MyData > 0 &&
                l == 0 ) {
                NSString *integerString = @"";
                if (moneyStr.length > 3) {
                    integerString = integerArray[moneyStr.length-4];
                }
                [M appendString:[NSString stringWithFormat:@"%@%@",integerString,@"元整"]];
                break;
            }
        }
        
        if([[moneyStr substringFromIndex:moneyStr.length-i+1] integerValue]==0
           && i != 1
           && i != 2)
        {
            [M appendString:@"元整"];
            break;
        }
        [M appendString:MyScale[i-1]];
    }
    return M;
}

- (NSString *)bankFormat
{
    if (!self && self.length < 18) {
        return self;
    }
    
    NSString *text = self;
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    return newString;
}

//正则验证是否正确
- (BOOL)evaluateWithRegStr:(NSString *)regStr replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) return YES;  // 始终允许用户删除
    
    NSString *amountText = [self stringByAppendingString:string];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regStr];
    return [predicate evaluateWithObject:amountText];
}

/**
 * 金额、可输入两位小数
 * @params maxAmount 最大金额
 * @params string 当前输入的字符
 * @Retrun result 是否可以进行编辑
 */
- (BOOL)regTwoDecimalPlacesAmountWithMaxAmount:(NSInteger)maxAmount replacementString:(NSString *)string maxAmountErrorBlock:(void (^)())maxAmountErrorBlock matchErrorBlock:(void (^)())matchErrorBlock
{
    NSString *regStr = @"^([0-9][\\d]{0,100})(\\.[\\d]{0,2})?$";
    BOOL match = [self evaluateWithRegStr:regStr replacementString:string];
    NSString *amountText = [self stringByAppendingString:string];
//    NSString *tmpStr = [amountText stringByAppendingString:string];
    NSString *numStr = [[amountText componentsSeparatedByString:@"."] firstObject];
    NSInteger amount = [numStr integerValue];
    if (([amountText integerValue] == maxAmount) && (![string isEqualToString:@""])) return NO;
    BOOL result = [amountText isEqualToString:@""] ? YES : (match && ((amount <= maxAmount) || [string isEqualToString:@"."]));
    if (!result){
        if (!match && matchErrorBlock) {
            matchErrorBlock();
        }else if (!(amount <= maxAmount) && maxAmountErrorBlock) {
            maxAmountErrorBlock();
        }
    }
    return result;
}

+ (NSMutableAttributedString *)title:(NSString *)title value:(NSString *)value titleColor:(UIColor *)titleColor valueColor:(UIColor *)valueColor
{
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", title, value]];
    [text addAttribute: NSForegroundColorAttributeName value: titleColor range: NSMakeRange(0, title.length)];
    [text addAttribute: NSForegroundColorAttributeName value: valueColor range: NSMakeRange(title.length, value.length)];
    return text;
}

@end
